package com.zsp.controller.common;

import com.zsp.config.MyConfig;
import com.zsp.entity.vo.AjaxResult;
import com.zsp.exception.FileNameLengthLimitExceededException;
import com.zsp.exception.FileSizeLimitExceededException;
import com.zsp.exception.InvalidExtensionException;
import com.zsp.service.FileUploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private FileUploadService fileUploadService;
    private static final String FILE_DELIMETER = ",";

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 例子：/profile/upload/2024/07/18/登录_20240718102038A001.png
            String fileName = fileUploadService.upload(file, MyConfig.getUploadPath());
            // 拼接：域名+端口+映射后的文件名
            String url = getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = MyConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = fileUploadService.upload(file, filePath);
                String url = getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 获取文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi.png
     *
     * @param fileName 路径名称
     * @return 没有文件路径的名称
     */
    public static String getName(String fileName)
    {
        if (fileName == null)
        {
            return null;
        }
        int lastUnixPos = fileName.lastIndexOf('/');
        int lastWindowsPos = fileName.lastIndexOf('\\');
        int index = Math.max(lastUnixPos, lastWindowsPos);
        return fileName.substring(index + 1);
    }
    public String getUrl() {
        // 获取当前请求对象
        HttpServletRequest request = getRequest();
        // 获取请求的域名和端口
        return getDomain(request);
    }
    public static HttpServletRequest getRequest()
    {
        return getRequestAttributes().getRequest();
    }
    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }


    public static String getDomain(HttpServletRequest request) {
        // 获取请求的完整 URL
        StringBuffer url = request.getRequestURL();
        // 获取应用程序的上下文路径
        String contextPath = request.getServletContext().getContextPath();
        // 删除 URL 中的请求路径部分，只保留域名和端口
        url.delete(url.length() - request.getRequestURI().length(), url.length());
        // 在 URL 末尾追加上下文路径
        url.append(contextPath);
        // 返回最终的域名和端口
        return url.toString();
    }
}
